<template>
  <div class="inner">
    <PageTitle title="拣货管理" />
    <div class="ibody">
      <div class="ib-cont">
        <div class="btn-group">
          <!-- <el-date-picker
            v-model="searchDate"
            type="date"
            placeholder="选择日期"
            :shortcuts="shortcuts"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="dateChange"
          /> -->

          <whDatePicker @change="dateChange" />

          <div
            class="wh-btn border-none primary large"
            type="primary"
            @click="createNewJHOrder"
            size="large"
          >
            创建拣货单
          </div>
        </div>
        <div class="data-table mt20">
          <el-table
            :data="sortingsData.list"
            style="width: 100%"
            row-class-name="table-normal-row"
            header-row-class-name="table-header-row"
          >
            <el-table-column
              prop="orderfillSortingNo"
              label="单号"
              width="140"
            />
            <el-table-column
              prop="shippingAddress"
              label="配送点"
              width="180"
            />
            <el-table-column prop="createTime" label="创建时间" width="220" />
            <el-table-column prop="orderfillCount" label="包裹数" width="80" />
            <el-table-column prop="status" label="拣货状态" width="120" />
            <el-table-column label="拣货员">
              <template #default="scope">
                {{ scope.row.picker || "--" }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
              <template #default="scope">
                <div class="btn-group">
                  <div
                    class="wh-btn border-solid primary"
                    v-if="scope.row.status === '待拣货'"
                    @click="completeJianHuo(scope.row.sortingId)"
                  >
                    完成
                  </div>
                  <div
                    class="wh-btn border-solid"
                    @click="goSortingSummaryPage(scope.row.sortingId)"
                  >
                    查看
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              layout="prev, pager, next"
              :total="sortingsData.total"
              @current-change="pageCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="creatDialogVisible"
      class="create-sort-dialog"
      width="700"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="dia-header">
          <h4 :id="titleId" :class="titleClass">创建拣货单</h4>
          <el-icon @click="close" class="el-icon--left"><Close /></el-icon>
        </div>
      </template>
      <el-row>
        <el-col :span="6" class="label">选择配送点</el-col>
        <el-col :span="18">
          <el-select
            class="dlselect"
            v-model="shippingAddress"
            placeholder="请选择配送点"
            size="large"
          >
            <el-option
              v-for="item in deliveryList"
              :key="item.id"
              :label="item.label"
              :value="item.id + '|||' + item.deliveryDate"
            />
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6" class="label">拣货单数量</el-col>
        <el-col :span="18">
          <div class="btn-group">
            <div
              :class="['wh-btn', newCount === 1 ? 'active' : '']"
              @click="changeNewCount(1)"
            >
              1
            </div>
            <div
              :class="['wh-btn', newCount === 2 ? 'active' : '']"
              @click="changeNewCount(2)"
            >
              2
            </div>
            <div
              :class="['wh-btn', newCount === 3 ? 'active' : '']"
              @click="changeNewCount(3)"
            >
              3
            </div>
            <div
              :class="['wh-btn', newCount === 4 ? 'active' : '']"
              @click="changeNewCount(4)"
            >
              4
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row class="mt20">
        <el-col :span="6" class="label">每单包裹数</el-col>
        <el-col :span="18">
          <div class="btn-group">
            <div
              :class="['wh-btn', orderfillCount === 6 ? 'active' : '']"
              @click="changeOrderFillCount(6)"
            >
              6
            </div>
            <div
              :class="['wh-btn', orderfillCount === 7 ? 'active' : '']"
              @click="changeOrderFillCount(7)"
            >
              7
            </div>
            <div
              :class="['wh-btn', orderfillCount === 8 ? 'active' : '']"
              @click="changeOrderFillCount(8)"
            >
              8
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row class="mt20">
        <!-- <el-col :span="6" class="label" /> -->
        <el-col :span="24">
          <div class="btn-group btn-group-nwidth">
            <el-button @click="submitCreate" size="large" type="primary"
              >确定</el-button
            >
            <el-button class="btn-calcel" @click="cancelSubmit" size="large"
              >取消</el-button
            >
          </div>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="6" class="label">电子拣货单： </el-col>
        <el-col :span="18">
          <el-switch
            v-model="isElectronic"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          {{ isElectronic ? "不打印纸质拣货单" : "打印并使用纸质拣货单" }}
        </el-col>
      </el-row> -->
    </el-dialog>
    <el-dialog
      v-model="completeDialogVisible"
      class="complete-sort-dialog"
      width="700"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="icon">
        <el-image :src="quesPng" />
      </div>
      <div class="title">确定完成拣货？</div>
      <div class="btn-group">
        <div class="sub-btn primary" @click="submitComplete">确定</div>
        <div class="sub-btn info" @click="cancelComplete">取消</div>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import PageTitle from "@/components/PageTitle.vue";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getSortingListApi, postSortingOrderApi } from "@/api/sorting";
import { useUserStoreHook } from "@/store/modules/user";
import dayjs from "dayjs";
import { getDeliveryListApi } from "@/api/delivery";
import { saveStorage, getStorage } from "@/utils/storage";
import { ElMessage, ElMessageBox } from "element-plus";
import { Warning, Close } from "@element-plus/icons-vue";
import {
  getSortingSummaryDetailApi,
  postSortingSummaryApi
} from "@/api/sorting";
import quesPng from "@/assets/img/ques.png";
import whDatePicker from "@/components/whDatePicker.vue";
import { myDialogSecond } from "@/components/myDialogSecond";
import { myDialog } from "@/components/myDialog";
// const today = getStorage("jianhuo-searchData") || dayjs().format("YYYY-MM-DD");
const today = dayjs().format("YYYY-MM-DD");
const userStore = useUserStoreHook();
const warehouseId = userStore.userInfo.warehouseId;
const userId = userStore.userInfo.user;

const creatDialogVisible = ref(false);
const router = useRouter();
const tempNewCount = getStorage("newCount");
const tempOrderfillCount = getStorage("orderfillCount");

const newCount = ref(tempNewCount || "1");
const orderfillCount = ref(tempOrderfillCount || "6");
const tempIsElectronic = getStorage("isElectronic") === "0" ? false : true;
const isElectronic = ref(tempIsElectronic);
const searchDate = ref(today);
const completeSortingId = ref("");
const completeDialogVisible = ref(false);

// 分页相关数据
const skip = ref(0);
const limit = ref(25);

const sortingsData = ref({
  total: 0,
  list: []
});

// 配送点
const deliveryList = ref<any>([]);

const shippingAddress = ref("");

async function getSortingList() {
  const queryObj = {
    warehouseId,
    queryDate: searchDate.value,
    skip: skip.value,
    limit: limit.value,
    type: 1
  };
  saveStorage("jianhuo-searchData", searchDate.value);
  try {
    sortingsData.value = await getSortingListApi(queryObj);
  } catch (error) {
    // ElMessageBox.alert("服务中止，请稍后重试", "提示", {
    //   type: "warning",
    //   icon: Warning
    // });
    myDialog.warning({
      message: "服务中止，请稍后重试！"
    });
  }
}

// 开始扫码
function startScan(sortingNo) {
  router.push({ path: "/fenjian/fjCheck", query: { sortingNo: sortingNo } });
}

function createNewJHOrder() {
  creatDialogVisible.value = true;
}

async function submitCreate() {
  if (!shippingAddress.value) {
    ElMessage.error("配送点不能为空");
    return;
  }
  if (!newCount.value) {
    ElMessage.error("新建拣货单数量不能为空");
    return;
  }
  if (!orderfillCount.value) {
    ElMessage.error("每拣货处理包裹量不能为空");
    return;
  }
  await postSortingOrderApi({
    warehouseId,
    shippingAddress: shippingAddress.value.split("|||")[0],
    userId,
    newCount: newCount.value,
    orderfillCount: orderfillCount.value,
    isElectronic: 1, // 修改需求后默认全部打印
    printOrderfill: 1,
    printOrderfillLabel: 1,
    printOrderfillSorting: 1
  });
  // 把选择的值暂存数据库
  saveStorage("newCount", newCount.value);
  saveStorage("orderfillCount", orderfillCount.value);

  creatDialogVisible.value = false;

  myDialogSecond.show({});

  // ElMessage({
  //   message: "创建成功，返回列表",
  //   type: "success"
  // });
  init();
}

function pageCurrentChange(val) {
  skip.value = limit.value * val - 1;
  getSortingList();
}

function dateChange(value) {
  searchDate.value = value;
  getSortingList();
}

async function getDeliveryList() {
  deliveryList.value = await getDeliveryListApi(warehouseId);
  deliveryList.value.forEach(item => {
    const tempDate = dayjs(item.deliveryDate);
    const cnDate = tempDate.month() + 1 + "月" + tempDate.date() + "日";
    item.label = item.name + "（" + cnDate + "，" + item.amount + "个）";
  });
}

function goSortingSummaryPage(sortingId) {
  router.push({ path: "/fenjian/summary", query: { sortingId } });
}
// 完成拣货
async function completeJianHuo(sortingId) {
  completeSortingId.value = sortingId;
  completeDialogVisible.value = true;

  // await postSortingSummaryApi(sortingId, userId);
  // ElMessage({
  //   type: "success",
  //   message: "完成拣货"
  // });
  // completeDialogVisible.value = false;
  // router.push({ path: "/jianhuo/list" });
}

function changeNewCount(tempNewCount) {
  newCount.value = tempNewCount;
}

async function submitComplete() {
  await postSortingSummaryApi(completeSortingId.value, userId);
  ElMessage({
    type: "success",
    message: "完成拣货"
  });
  completeDialogVisible.value = false;
  init();
  // router.push({ path: "/jianhuo/list" });
}

async function cancelComplete() {
  completeSortingId.value = "";
  completeDialogVisible.value = false;
}

function changeOrderFillCount(tempNum) {
  orderfillCount.value = tempNum;
}

function cancelSubmit() {
  creatDialogVisible.value = false;
}

function init() {
  getSortingList();
  getDeliveryList();
}

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
.inner {
  .ibody {
    .ib-cont {
      background-color: white;
      border-radius: 10px;
      padding: 30px;
      .btn-group {
        display: flex;
        align-items: center;
        justify-content: space-between;
        :deep(.el-date-editor) {
          width: 200px;
          height: 50px;
          color: #3f4254;
          background: #f9f9f9;
          .el-input__wrapper {
            height: 50px;
            color: #3f4254;
            background: #f9f9f9;
            .el-icon {
              font-size: 24px;
              color: #3f4254;
            }
          }
        }
      }
      :deep(.data-table) {
        font-family: 思源黑体;
        font-size: 18px !important;
        font-weight: normal;
        letter-spacing: 0em;
        color: #3f4254 !important;
        .table-header-row {
          font-family: 思源黑体;
          font-size: 18px;
          font-weight: bold;
          text-align: right;
          letter-spacing: 0em;
          color: #b5b5c3;
          border-style: dashed;
        }
        .table-normal-row {
          border-bottom: 1px dashed #d8d8d8;
          &::after {
            display: none;
          }
          &::before {
            display: none;
          }
        }
        .el-table__cell {
          border-bottom: 1px dashed #d8d8d8 !important;
        }
        .pagination {
          display: flex;
          margin-top: 20px;
          justify-content: flex-end;
        }
      }
    }
  }
}
:deep(.create-sort-dialog) {
  border-radius: 10px;
  .el-dialog__header {
    width: 100%;
    padding: 0px;
    height: 70px;
    line-height: 70px;
    border-radius: 10px 10px 0px 0px;
    box-shadow: 0px 1px 0px 0px rgba(0, 0, 0, 0.15);
    border-bottom: 0.5px solid #d8d8d8;
    .dia-header {
      position: relative;
      height: 70px;
      line-height: 70px;
      h4 {
        font-family: 思源黑体;
        font-size: 28px;
        font-weight: bold;
        text-align: center;
        letter-spacing: 0em;
        color: #3d3d3d;
        width: 100%;
        height: 70px;
        line-height: 70px;
      }
      .el-icon {
        position: absolute;
        right: 20px;
        font-size: 32px;
        top: 20px;
      }
    }
  }
  .el-dialog__body {
    padding: 0px;
    box-sizing: border-box;
    .el-row {
      box-sizing: border-box;
      height: 80px;
      line-height: 80px;
      border-bottom: 0.5px dashed #d8d8d8;
      &:last-child {
        border: none;
      }
      .label {
        text-align: right;
        font-family: 思源黑体;
        font-size: 18px;
        font-weight: bold;
        letter-spacing: 0em;
        color: #b5b5c3;
        padding-right: 20px;
      }
      .el-select {
        width: 336px;
        font-family: 思源黑体;
        font-size: 18px;
        font-weight: bold;
      }

      .btn-group {
        display: flex;
        height: 80px;
        align-items: center;
        &.btn-group-nwidth {
          justify-content: center;
          .el-button {
            width: 200px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            font-family: 思源黑体;
            font-size: 18px;
            font-weight: bold;
            &.btn-calcel {
              background: #d8d8d8;
              color: white;
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="scss">
.complete-sort-dialog {
  .icon {
    display: flex;
    align-items: center;
    justify-content: center;
    .el-image {
      width: 100px;
      height: 100px;
    }
  }
  .title {
    font-family: Source Han Sans CN;
    font-size: 22px;
    font-weight: bold;
    text-align: center;
    letter-spacing: 0em;

    color: #3f4254;
    margin-top: 24px;
  }
  .btn-group {
    margin: auto;
    margin-top: 60px;
    width: 500px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    .sub-btn {
      width: 200px;
      height: 50px;
      border-radius: 4px;
      text-align: center;
      line-height: 50px;
      color: white;
      cursor: pointer;
      &.primary {
        background: #3689f5;
      }
      &.info {
        background: #d8d8d8;
      }
    }
  }
}
</style>
